package com.voice.core.connection.frame;

import com.voice.core.connection.Connection;
import com.voice.core.utils.BytesUtil;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class HeaderFrame extends AbstractFrame{

    public HeaderFrame(){}

    public HeaderFrame(byte[] bytes,int streamId,boolean endStream){
        this((byte)0,(byte)0,(byte)0,(byte)0,bytes,streamId,endStream);
    }

    public HeaderFrame(byte paddingLength,byte e,int streamDependency,byte weight,byte[] bytes,int streamId,boolean endStream){
          this.streamId=streamId;
        this.type=FrameType.headers.getType();
        this.length=bytes.length+paddingLength+6;
        padded(paddingLength!=0);
        endOfStream(endStream);
        endHeaders(true);
        if(weight!=0||streamDependency!=0||e!=0) priority(true);
        ByteBuffer buffer=ByteBuffer.allocate(length+headerLength);
        buffer.put(BytesUtil.intToBytes(length,3));
        buffer.put(type);
        buffer.put(flag);
        buffer.putInt(streamId);
        buffer.put(paddingLength);
        if(weight!=0||streamDependency!=0||e!=0){
            buffer.putInt((e<<31)&streamDependency);
            buffer.put(weight);
        }
        buffer.put(bytes);
        buffer.put(new byte[paddingLength]);
        this.payload=buffer.array();
    }

    @Override
    public void onFinish(Connection connection) {
        connection.onHeadersRead(streamId,getData(),getWeight(),endOfStream());
    }

    @Override
    public byte[] getData() {
        if(priority()&&padded()) return Arrays.copyOfRange(payload, headerLength+6,payload.length-getPaddingLength());
        if(priority()&&!padded()) return Arrays.copyOfRange(payload, headerLength+6,payload.length);
        if(!priority()&&padded()) return Arrays.copyOfRange(payload, headerLength,payload.length-getPaddingLength());
        return Arrays.copyOfRange(payload, headerLength,payload.length);
    }

}
